package com.Txunda.fxw.ui.activity.other;

import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.Txunda.fxw.R;
import com.Txunda.fxw.base.utils.util.StringUtils;
import com.Txunda.fxw.ui.base.BaseAty;
import com.Txunda.fxw.ui.toolkit.util.DensityUtil;
import com.Txunda.fxw.ui.toolkit.util.PreferenceUtil;
import com.Txunda.fxw.ui.widget.XCSlideView;
import com.Txunda.fxw.view.RoundedImageView;
import com.Txunda.fxw.view.dialog.AlertDialog;
import com.bumptech.glide.Glide;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * 特色餐饮
 *
 * @author Administrator
 */
public class FeaturesAty extends BaseAty implements PlatformActionListener {

    @ViewInject(R.id.aty_title3_tv_center)
    private TextView aty_title3_tv_center;
    private String from;
    private XCSlideView mSlideViewRight;
    private float mScreenHeight;
    private LinearLayout linear_top;
    private LinearLayout linear_bottom;
    @ViewInject(R.id.icon_logo)
    private RoundedImageView icon_logo;

    @ViewInject(R.id.feature_web)
    private WebView feature_web;
    Drawable img_collect;
    Drawable img_not_collect;
    private boolean isCollect;
    /**
     * 历史收藏
     */
    protected String history;
    @SuppressLint("HandlerLeak")
    Handler handler2 = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    showToast("微博分享成功");
                    finish();
                    break;
                case 2:
                    showToast("成功分享给微信好友");     //分享到微信
                    finish();
                    break;
                case 3:
                    showToast("朋友圈分享成功");     //分享到微信朋友圈
                    finish();
                    break;
                case 4:
                    showToast("QQ空间分享成功");
                    finish();
                    break;
                case 5:
                    showToast("分享已取消");
                    break;
                case 6:
                    showToast("分享失败");
                    break;
                default:
                    break;
            }
        }
    };
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 1:
                    linear_top.setVisibility(View.VISIBLE);
                    linear_bottom.setVisibility(View.GONE);
                    ValueAnimator animator2 = ValueAnimator.ofFloat(0, mScreenHeight);
                    animator2.setTarget(linear_bottom);
                    animator2.setDuration(1000).start();
                    animator2.addUpdateListener(new AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animation) {
                            linear_bottom.setTranslationY((Float) animation.getAnimatedValue());
                        }
                    });
                    break;

                default:
                    break;
            }

        }
    };
    private String per_content;
    private String special_food_content;
    private String cut_brand;
    private String cut_product;
    private TextView tv_collect;
    private String com_id;


    private SharedPreferences sp;
    private SharedPreferences.Editor edit;
    private String collect_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WebSettings set = feature_web.getSettings();
        set.setTextSize(WebSettings.TextSize.SMALLER);
        if ("1".equals(from)) {
            feature_web.loadDataWithBaseURL(null, per_content, "text/html", "utf-8", null);
        } else if ("3".equals(from)) {
            feature_web.loadDataWithBaseURL(null, special_food_content, "text/html", "utf-8", null);
        } else if ("5".equals(from)) {
            feature_web.loadDataWithBaseURL(null, cut_brand, "text/html", "utf-8", null);
        } else if ("4".equals(from)) {
            feature_web.loadDataWithBaseURL(null, cut_product, "text/html", "utf-8", null);
        } else if ("2".equals(from)) {
            feature_web.loadDataWithBaseURL(null, special_food_content, "text/html", "utf-8", null);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        collect_id = sp.getString("history_collect", "");
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.aty_features;
    }

    @Override
    protected void initialized() {
        sp = getSharedPreferences("COLLECT", Activity.MODE_PRIVATE);
        edit = sp.edit();

        img_collect = getResources().getDrawable(R.drawable.icon_yet_collect);   //收藏图标
        img_not_collect = getResources().getDrawable(R.drawable.icon_collect3);   //未收藏图标
        img_collect.setBounds(0, 0, img_collect.getMinimumWidth(), img_collect.getMinimumHeight());
        img_not_collect.setBounds(0, 0, img_not_collect.getMinimumWidth(), img_not_collect.getMinimumHeight());

        String logo = PreferenceUtil.readString(getApplicationContext(), PreferenceUtil.sp_logo);
        Glide.with(this).load(logo).into(icon_logo);
        from = getIntent().getStringExtra("from");
        com_id = getIntent().getStringExtra("com_id");    //.商家id
        if ("1".equals(from)) {
            aty_title3_tv_center.setText("人均消费");
            per_content = getIntent().getStringExtra("per_content");   //人均消费web页面
        } else if ("2".equals(from)) {
            special_food_content = getIntent().getStringExtra("special_food_content");
            aty_title3_tv_center.setText("推荐");
        } else if ("3".equals(from)) {
            special_food_content = getIntent().getStringExtra("special_food_content");   //特色餐饮
            aty_title3_tv_center.setText("推荐");
        } else if ("4".equals(from)) {
            cut_product = getIntent().getStringExtra("cut_product");   //产品
            aty_title3_tv_center.setText("产品");
        } else if ("5".equals(from)) {
            cut_brand = getIntent().getStringExtra("cut_brand");   //品牌
            aty_title3_tv_center.setText("品牌");
        }

        // 动画
        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        mScreenHeight = outMetrics.heightPixels;
        // 侧滑
        Context mContext = this;
        // 屏幕宽度
        int mScreenWidth = DensityUtil.getScreenWidthAndHeight(mContext)[0];
        mSlideViewRight = XCSlideView.create(FeaturesAty.this, XCSlideView.Positon.RIGHT);
        View menuViewRight = LayoutInflater.from(mContext).inflate(R.layout.layout_slide, null);
        tv_collect = menuViewRight.findViewById(R.id.tv_collect);    //收藏
        collect_id = sp.getString("history_collect", "");
        isCollect = collect_id.contains(com_id);
        if (collect_id.contains(com_id)) {    //未收藏
            tv_collect.setText("已收藏");
            tv_collect.setCompoundDrawables(null, img_collect, null, null);

        } else {   //已收藏
            tv_collect.setText("收藏");
            tv_collect.setCompoundDrawables(null, img_not_collect, null, null);

        }
        tv_collect.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                collect_id = sp.getString("history_collect", "");
                isCollect = collect_id.contains(com_id);
                if (!isCollect) {    //未收藏
                    tv_collect.setText("已收藏");
                    tv_collect.setCompoundDrawables(null, img_collect, null, null);
                    //保存商家id的值
                    history = sp.getString("history_collect", "");
                    if (StringUtils.isEmpty(history)) {
                        history = com_id;
                    } else {
                        history += "," + com_id;
                    }
                    edit.putString("history_collect", history);
                    edit.apply();

                } else {   //收藏
                    tv_collect.setText("收藏");
                    tv_collect.setCompoundDrawables(null, img_not_collect, null, null);

                    //去掉商家id的值
                    history = sp.getString("history_collect", "");

                    if (history.contains(com_id + ",")) {
                        history = history.replace(com_id + ",", "");
                    } else if (history.contains("," + com_id)) {
                        history = history.replace("," + com_id, "");
                    } else if (history.contains(com_id)) {
                        history = history.replace(com_id, "");
                    }

                    edit.putString("history_collect", history);
                    edit.commit();

                }

            }
        });

        //======================================================

        mSlideViewRight.setMenuView(FeaturesAty.this, menuViewRight);
        mSlideViewRight.setMenuWidth(mScreenWidth * 3 / 9);
        LinearLayout linear_phone = menuViewRight.findViewById(R.id.linear_phone);
        LinearLayout leave_linear = menuViewRight.findViewById(R.id.linear_leave);
        LinearLayout linear_share = menuViewRight.findViewById(R.id.linear_share);
        linear_top = menuViewRight.findViewById(R.id.linear_top);
        linear_bottom = menuViewRight.findViewById(R.id.linear_bottom);
        LinearLayout linear_share2 = menuViewRight.findViewById(R.id.linear_share2);
        LinearLayout linear_setting = menuViewRight.findViewById(R.id.linear_setting);
        LinearLayout linear_weibo = menuViewRight.findViewById(R.id.linear_weibo);
        LinearLayout linear_qq = menuViewRight.findViewById(R.id.linear_qq);
        LinearLayout linear_weixin = menuViewRight.findViewById(R.id.linear_weixin);
        LinearLayout linear_friends = menuViewRight.findViewById(R.id.linear_friends);
        //微信分享
        linear_weixin.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //判断是否安装微信
                if (isWeixinAvilible()) {
                    ShareParams sp_hy = new ShareParams();
                    sp_hy.setShareType(Platform.SHARE_WEBPAGE); // 非常重要：一定要设置分享属性
                    sp_hy.setTitle("峰行网"); // 分享标题
                    sp_hy.setText("峰行网超好用-分享给朋友吧~");// 分享文本
                    sp_hy.setUrl("https://www.txunda.com");
                    sp_hy.setImageData(BitmapFactory.decodeResource(getResources(), R.drawable.icon_logo));
                    // 3、非常重要：获取平台对象
                    Platform wechathy = ShareSDK.getPlatform(Wechat.NAME);
                    wechathy.setPlatformActionListener(FeaturesAty.this); // 设置分享事件回调
                    // 执行分享
                    wechathy.share(sp_hy);
                } else {
                    showToast("请下载并安装微信客户端");
                }

            }
        });

        //朋友圈分享
        linear_friends.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (isWeixinAvilible()) {
                    ShareParams sp = new ShareParams();
                    sp.setShareType(Platform.SHARE_WEBPAGE); // 非常重要：一定要设置分享属性
                    sp.setTitle("峰行网"); // 分享标题
                    sp.setText("峰行网超好用-分享给朋友吧~");// 分享文本
                    sp.setUrl("https://www.txunda.com");
                    sp.setImageData(BitmapFactory.decodeResource(getResources(), R.drawable.icon_logo));
                    //sp.setImagePath();
                    // 3、非常重要：获取平台对象
                    Platform wechatMoments = ShareSDK.getPlatform(WechatMoments.NAME);
                    wechatMoments.setPlatformActionListener(FeaturesAty.this); // 设置分享事件回调
                    // 执行分享
                    wechatMoments.share(sp);
                } else {
                    showToast("请下载并安装微信客户端");
                }

            }
        });
        //qq分享
        linear_qq.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (isQQClientAvailable()) {
                    ShareParams sp1 = new ShareParams();
                    sp1.setTitle("峰行网");// 分享标题
                    sp1.setText("峰行网超好用-分享给朋友吧~");// 分享文本
                    sp1.setImageData(BitmapFactory.decodeResource(getResources(), R.drawable.icon_logo));
                    sp1.setTitleUrl("https://www.txunda.com"); // 网友点进链接后，可以看到分享的详情
                    sp1.setSite("峰行网");
                    sp1.setSiteUrl("https://www.txunda.com");
                    // 3、非常重要：获取平台对象
                    Platform qzone = ShareSDK.getPlatform(QQ.NAME);
                    qzone.setPlatformActionListener(FeaturesAty.this);
                    // 执行分享
                    qzone.share(sp1);
                } else {
                    showToast("请下载并安装QQ客户端");
                }

            }
        });
        //微博分享
        linear_weibo.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                showTips(R.drawable.error, "敬请期待");

            }
        });
        //设置
        linear_setting.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(SettingAty.class, null);

            }
        });
        //电话
        linear_phone.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                new AlertDialog(FeaturesAty.this).builder().setTitle("提示").setMsg("tel: 022-60688296")
                        .setPositiveButton("确认", new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel: 022-60688296"));
                                startActivity(intent);

                            }
                        }).setNegativeButton("取消", new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                    }
                }).show();

            }
        });
        // 分享
        linear_share.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 向上走的动画
                if (linear_top.getVisibility() == View.VISIBLE) {

                    linear_top.setVisibility(View.GONE);
                    linear_bottom.setVisibility(View.VISIBLE);
                    ValueAnimator animator = ValueAnimator.ofFloat(mScreenHeight / 2, 0);
                    animator.setTarget(linear_bottom);
                    animator.setDuration(500).start();
                    animator.addUpdateListener(new AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animation) {
                            linear_bottom.setTranslationY((Float) animation.getAnimatedValue());
                        }
                    });
                }

            }
        });
        linear_share2.setOnClickListener(new OnClickListener() {
            private Timer timer;
            private TimerTask timetask;

            @Override
            public void onClick(View v) {

                if (linear_top.getVisibility() == View.GONE) {
                    linear_top.setVisibility(View.VISIBLE);
                    linear_bottom.setVisibility(View.GONE);
                    float start = 0 - mScreenHeight;
                    ValueAnimator animator = ValueAnimator.ofFloat(start, 0);
                    animator.setTarget(linear_top);
                    animator.setDuration(500).start();
                    animator.addUpdateListener(new AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animation) {
                            linear_top.setTranslationY((Float) animation.getAnimatedValue());
                        }
                    });
                    timer = new Timer();
                    timetask = new TimerTask() {

                        @Override
                        public void run() {
                            Message msg = new Message();
                            msg.what = 1;
                            handler.sendMessage(msg);
                        }
                    };
                    timer.schedule(timetask, 300);

                }

            }
        });
        // 评价
        leave_linear.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(LeaveMessageAty.class, null);
            }
        });
    }

    @Override
    @OnClick({R.id.icon_logo})
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.icon_logo:
                if (!mSlideViewRight.isShow())
                    mSlideViewRight.show();
                break;

            default:
                break;
        }
    }

    @Override
    protected void requestData() {

    }


    @Override
    public void onCancel(Platform arg0, int arg1) {
        handler2.sendEmptyMessage(5);         //取消分享

    }

    @Override
    public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
        if (arg0.getName().equals(SinaWeibo.NAME)) {// 判断成功的平台是不是新浪微博
            handler2.sendEmptyMessage(1);            //分享到微博
        } else if (arg0.getName().equals(Wechat.NAME)) {
            handler2.sendEmptyMessage(2);               //分享给微信好友
        } else if (arg0.getName().equals(WechatMoments.NAME)) {
            handler2.sendEmptyMessage(3);               //分享到微信朋友圈
        }
//        else if (arg0.getName().equals(QZone.NAME)) {
//            handler2.sendEmptyMessage(4);      //分享到qq空间
//        }

    }

    @Override
    public void onError(Platform arg0, int arg1, Throwable arg2) {
        arg2.printStackTrace();
        Message msg = new Message();
        msg.what = 6;
        msg.obj = arg2.getMessage();
        handler2.sendMessage(msg);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ShareSDK.stopSDK();
    }


}
